module ApplicationHelper
  # 是否当前路径
  def current_nav_class(key, options = {})
    options.reverse_merge!(:current => 'uk-active', :not_current => '')
    is_current_nav?(key, options) ? options[:current] : options[:not_current]
  end

  def is_current_nav?(key, options = {})
    @current_nav_keys ||= MenuNav.menus_nav[controller.controller_path].try('[]', action_name) || []
    is_current = @current_nav_keys.include?(key.to_s)
    if options[:if]
      is_current = is_current && options[:if].call
    end
    is_current
  end

  def can_entrance?(ctl, action, admin)
    return false unless admin.role.present?
    AbilityData.convert_ability_data(ctl, action, admin.role)
  end

  # pc上传组件
  def webuploader_image(name, label: '上传', type: 'image', id: 'webuploader', klass: '', asset: nil)
    html = %{
      <div id="#{id}" class="upload-wrap webuploader #{klass}" data-name="#{name}" data-url="#{uploads_path}" data-type="#{type}">
        <div class="upload-body">
          <ul class="upload-list">
          }
    [asset].flatten.compact.each do |at| # .select {|a| !a.new_record?}
      a = Asset.find_by(id: at['id'] || at.try(:id))
      if a.present?
        html << %{
                <li id="#{a.try(:id)}" class="file-item thumbnail">
                  #{link_to 'x', upload_path(a, file_id: a.try(:id), protect_token: a.try(:protect_token)), method: :delete, remote: true, class: 'delete'}
        #{hidden_field_tag name, a.try(:id)}
        #{image_tag a.try(:file_url)}
                </li>
              }
      end
    end

    html << %{
            <li class="upload-pick">
              <span>＋</span>
              <strong>#{label}</strong>
            </li>
          </ul>
        </div>
      </div>
    }
    html.html_safe
  end

  # pc上传附件
  def webuploader_file(name, label: '上传', type: 'image', id: 'webuploader', klass: 'webuploader', asset: nil)
    html = %{
        <div id="#{id}" class="uk-form-file file-upload-wrap #{klass}" data-name="#{name}" data-url="#{uploads_path}" data-type="#{type}">
          <div class="upload-body">
              <a class="upload-pick">
                <i class="uk-icon-cloud-upload uk-icon-medium uk-margin-small-right"></i>
                <strong>#{label}</strong>
              </a>
            <ul class="upload-list">
            }
    [asset].flatten.compact.each do |at| # .select {|a| !a.new_record?}
      a = Asset.find_by(id: at['id']  || at.try(:id))
      if a.present?
        html << %{
                  <li id="#{a.try(:id)}" class="file-item">
                    #{link_to 'x', upload_path(a, file_id: a.try(:id), protect_token: a.try(:protect_token)), method: :delete, remote: true, class: 'delete'}
        #{hidden_field_tag name, a.try(:id)}
      <div class="file-title">#{a.file_name} <small>#{a.file_size.to_i/1000000.0}MB</small></div>
                  </li>
                }
      end
    end
    html << %{
            </ul>
          </div>
        </div>
      }
    html.html_safe
  end

  # 手机端头像上传
  def mobileuploader_avatar(name, label: '上传图片', type: 'image', id: 'avatar_webuploader', klass: 'webuploader', asset: nil)
    html = %{
      <div id="#{id}" class="avatar-upload #{klass}" data-name="#{name}" data-url="#{uploads_path}" data-type="#{type}">
      <div class="upload-body">
        <ul class="upload-list upload-pick">
            }
    if asset
      [asset].flatten.compact.select { |a| !a.new_record? }.each do |a| # .select {|a| !a.new_record?}
        html << %{
                <li id="#{a.try(:id)}" class="file-item">
                    #{hidden_field_tag name, a.try(:id)}
        #{image_tag a.file.url}
                </li>
                  }
      end
    else
      html << %{
            <li class="file-item">
                #{hidden_field_tag name, nil}
      #{image_tag ''}
            </li>
              }
    end

    html << %{
              </ul>
            </div>
          </div>
      }
    html.html_safe
  end

  # 手机端上传组件
  def mobileuploader_single_image(name, label: '上传图片', type: 'image', id: 'webuploader', klass: 'webuploader', asset: nil)
    html = %{
        <div id="#{id}" class="mobile-single-upload-wrap #{klass}" data-name="#{name}" data-url="#{uploads_path}" data-type="#{type}">
          <div class="upload-body">
            <ul class="upload-list">
            }
    [asset].flatten.compact.each do |at| # .select {|a| !a.new_record?}
      a = Asset.find_by(id: at['id'] || at.try(:id))
      if a.present?
        html << %{
                  <li id="#{a.try(:id)}" class="file-item thumbnail">
      #{hidden_field_tag name, a.try(:id)}
        #{image_tag a.file.url}
                  </li>
                }
      end
    end
    html << %{
              <li class="upload-pick weui-uploader__input-box">
              </li>
            </ul>
          </div>
        </div>
      }
    html.html_safe
  end

  # 手机端上传组件
  def mobileuploader_image(name, label: '上传图片', type: 'image', id: 'webuploader', klass: 'webuploader', asset: nil)
    html = %{
        <div id="#{id}" class="mobile-upload-wrap #{klass}" data-name="#{name}" data-url="#{uploads_path}" data-type="#{type}">
          <div class="upload-body">
            <ul class="upload-list">
            }
    [asset].flatten.compact.each do |at| # .select {|a| !a.new_record?}
      a = Asset.find_by(id: at['id'] || at.try(:id))
      if a.present?
        html << %{
                  <li id="#{a.try(:id)}" class="file-item thumbnail">
      #{hidden_field_tag name, a.try(:id)}
        #{image_tag a.file.url}
                  </li>
                }
      end
    end
    html << %{
              <li class="upload-pick weui-uploader__input-box">
              </li>
            </ul>
          </div>
        </div>
      }
    html.html_safe
  end

  # 手机端上传组件
  def mobileuploader_file(name, label: '上传图片', type: 'image', id: 'webuploader', klass: 'webuploader', asset: nil)
    html = %{
        <div id="#{id}" class="mobile-upload-file #{klass}" data-name="#{name}" data-url="#{uploads_path}" data-type="#{type}">
          <div class="upload-body">
            <ul class="upload-list">
            }
    [asset].flatten.compact.each do |at| # .select {|a| !a.new_record?}
      a = Asset.find_by(id: at['id'] || at.try(:id))
      if a.present?
        html << %{
                  <li id="#{a.try(:id)}" class="file-item" style="text-align: center;">
                    #{link_to 'x', upload_path(a, file_id: a.try(:id), protect_token: a.try(:protect_token)), method: :delete, remote: true, class: 'delete'}
        #{hidden_field_tag name, a.try(:id)}
        #{image_tag 'icon_file.svg', style: 'width: 35px;height: auto;margin-top: 15px;'}
                  </li>
                }
      end
    end
    html << %{
              <li class="upload-pick weui-uploader__input-box">
              </li>
            </ul>
          </div>
        </div>
      }
    html.html_safe
  end

  # 腾讯云上传
  def qcloud_uploader(name, id: 'videouploader')
    html = %{
        <input type="hidden" name="#{name}_file_id"  id="#{name}_file_id" />
        <input type="hidden" name="#{name}_url" id="#{name}_url" />
        <div class="video-upload-wrap">
          <input id="#{id}" type="file" />
          <label for="#{id}" class="btn btn-primary">直接上传视频</label>
        </div>
        <div class="result-box" id="resultBox"></div>
      }
    html.html_safe
  end

  def paginate_info(paginated)
    "显示 #{start = (paginated.current_page - 1) * paginated.limit_value + 1} - #{start + paginated.count - 1} 条，共 #{paginated.total_count} 条"
  end

  def static_form_control(label, content)
    %{
    <div class="uk-form-row">
      <label class="uk-form-label">#{label}</label>
      <div class="uk-form-controls">
        <p style="margin-top: 5px;">
          #{content}
        </p>
      </div>
    </div>
    }.html_safe
  end

  def formatted_time(datetime)
    if Time.now - datetime  <= 5.minutes
      '刚刚'
    elsif Time.now - datetime < 30.minutes
      '5分钟前'
    elsif Time.now - datetime < 1.hour
      '30分钟前'
    elsif Time.now - datetime < 1.year
      datetime.strftime("%m月%d日 %H:%M:%S")
    else
      datetime.strftime("%Y年%m月%d日 %H:%M:%S ")
    end
  end

  def for_time(datetime)
    if datetime.present?
      datetime.strftime("%Y/%m/%d")
    end
  end

  def flatten_time(datetime)
    if datetime.present?
      datetime.strftime("%Y-%m-%d %H:%M")
    end
  end

  def flatten_date(datetime)
    if datetime.present?
      datetime.strftime("%Y-%m-%d")
    end
  end

  def api_time(datetime)
    if datetime.present?
      datetime.strftime("%Y年%m月%d日 %H:%M:%S ")
    end
  end

  ##金钱格式化显示为 123,456,789.00
  def format_money(money, precision=0, delimiter = nil)
    return '0.00' if money.nil?
    precision = 2
    number_to_currency(money, precision: precision, unit: "￥", separator:".", delimiter: delimiter || "")
  end

  def format_text(content)
    content.html_safe if content.present?
  end

  def format_distance(distance)
    return "#{distance.round(2)} m" if distance < 1000
    return "#{(distance/1000.0).round(2)} km" if distance > 1000
  end

  def hash_to_hidden_fields(hash)
    query_string = Rack::Utils.build_nested_query(hash)
    pairs        = query_string.split(Rack::Utils::DEFAULT_SEP)

    tags = pairs.map do |pair|
      key, value = pair.split('=', 2).map { |str| Rack::Utils.unescape(str) }
      hidden_field_tag(key, value)
    end

    tags.join("\n").html_safe
  end

end
